package com.chat.ui.recyclerview;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chat.MainActivity;
import com.chat.MyApplication;
import com.chat.R;
import com.chat.entity.DataPackage;
import com.chat.entity.Message;
import com.chat.entity.ServerAction;
import com.chat.entity.event.ChannelEvent;
import com.chat.net.SocketClient;
import com.chat.net.socket.Channel;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import io.netty.channel.ChannelHandlerContext;

/**
 * 聊天界面
 */
public class DetailFragment extends Fragment {

    private DetailViewModel mViewModel;
    RecyclerView recyclerView;
    private DetailFragment.MyRecycleViewAdapter adapter;
    private List<HashMap<String,Object>> list=new ArrayList<HashMap<String,Object>>();
    private List<HashMap<String,Object>> mData=new ArrayList<HashMap<String,Object>>();
    public static int id;//聊天室id
    boolean isActivite = false;//是否更新聊天记录
    Button send;
    EditText edit;
    int userId;



    public static DetailFragment newInstance() {
        return new DetailFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view=inflater.inflate(R.layout.fragment_detail, container, false);
        recyclerView = view.findViewById(R.id.detail_chat_recycler);
        id = getArguments().getInt("id");
        getData();
        userId = getContext().getSharedPreferences("chat", Context.MODE_PRIVATE).getInt("userId",4);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));//垂直线性布局
        adapter=new DetailFragment.MyRecycleViewAdapter();
        recyclerView.setAdapter(adapter);
        send = view.findViewById(R.id.detail_chat_send);
        edit = view.findViewById(R.id.detail_chat_edit);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //更新ui
                if(!edit.getText().toString().equals("")) {
                    String msg = edit.getText().toString();
                    Message message = new Message();
                    message.setMsg(msg);
                    message.setRoomId(id);
                    message.setUserId(userId);
                    message.setSendTime(new Date(Calendar.getInstance().getTimeInMillis()));

                    HashMap<String, Object> item = new HashMap<>();
                    item.put("name", "1");
                    item.put("message", msg);
                    item.put("isSender", false);
                    item.put("picture", R.drawable.dog);
                    mData.add(item);
                    edit.setText("");
                    adapter.notifyDataSetChanged();

                    //发送请求包
                    //聊天记录
                    DataPackage request = DataPackage.request(message,ServerAction.SEND_MESSAGE_FROM_ROOM);
                    SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
                        @Override
                        public synchronized void onChannelEvent(Channel ctx, DataPackage source) {
                            super.onChannelEvent(ctx, source);
                        }
                    }, request);
                }
            }
        });


        //menuItem
        MenuItem menuItem = MainActivity.toolbar.getMenu().getItem(2);
        menuItem.setTitle(R.string.action_folder);
        menuItem.setEnabled(true);
        return  view;
    }

    public void getData(){
        isActivite = true;
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(android.os.Message msg) {
                adapter.notifyDataSetChanged();
//                continueGetMessage();
            }
        };
        //获取聊天室聊天记录请求
        HashMap<String,Integer> a = new HashMap<>();
        a.put("roomId",id);
        DataPackage dataPackage = DataPackage.successResponse(a,ServerAction.GET_MESSAGE_FROM_ROOM);
//        ChatObjectServer.getServer().addObject(dataPackage);
        new Thread(()->{
//<<<<<<< HEAD
                while (isActivite) {
                    //获取聊天记录事件
                    SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
                        @Override
                        public synchronized void onChannelEvent(Channel ctx, DataPackage source) {
                            mData.clear();
                            if (source.getCode() == 200) {
                                List<Message> messages = (List<Message>) source.getDate();
                                for (Message message : messages) {
                                    HashMap<String, Object> item = new HashMap<>();
                                    item.put("name", String.valueOf(message.getUserId()));
                                    item.put("message", message.getMsg());
                                    item.put("isSender", message.getUserId() != userId);
                                    item.put("picture", R.drawable.dog);
                                    mData.add(item);
                                }
                                handler.sendMessage(android.os.Message.obtain());
//=======
//            int time = 0;
//            while(time++<10){
//                //获取聊天记录事件
//                SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
//                    @Override
//                    public synchronized void onChannelEvent(Channel ctx, DataPackage source) {
//                        mData.clear();
//                        if(source.getCode()==200){
//                            List<Message> messages = (List<Message>) source.getDate();
//                            for(Message message:messages){
//                                HashMap<String,Object> item = new HashMap<>();
//                                item.put("name",String.valueOf(message.getUserId()));
//                                item.put("message",message.getMsg());
//                                item.put("isSender",message.getUserId()!=userId);
//                                item.put("picture",R.drawable.dog);
//                                mData.add(item);
//>>>>>>> d40e431dc1f24bb84233c75a4a1d58d198a0063a
                            }
                        }
                    }, dataPackage);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        }).start();



    }

    class  MyRecycleViewAdapter extends RecyclerView.Adapter<DetailFragment.MyRecycleViewAdapter.ViewHolder>
    {


        public  class ViewHolder extends RecyclerView.ViewHolder {
            public ImageView left_head,right_head;
            public TextView message;
            public TextView left_name;

            public ViewHolder(View convertView) {
                super(convertView);
                left_head = (ImageView)convertView.findViewById(R.id.item_detail_left_head);
                message = (TextView)convertView.findViewById(R.id.item_detail_context);
                right_head = (ImageView) convertView.findViewById(R.id.item_detail_right_head);
                left_name = (TextView)convertView.findViewById(R.id.item_detail_left_name);
            }
        }

        @NonNull
        @Override
        public DetailFragment.MyRecycleViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v= LayoutInflater.from(getActivity()).inflate(R.layout.item_detail_chat,parent, false);
            return new ViewHolder(v);
        }





        @Override
        public void onBindViewHolder(@NonNull DetailFragment.MyRecycleViewAdapter.ViewHolder holder, final int position) {
            //picture
            holder.left_name.setText((String)mData.get(position).get("name"));
            holder.message.setText((String)mData.get(position).get("message"));
            if((boolean)mData.get(position).get("isSender")==true){
                Glide.with(getActivity()).load(new MyApplication().imagebaseurl+mData.get(position).get("picture").toString()).placeholder(R.drawable.dog).into(holder.left_head);
                holder.left_name.setVisibility(View.VISIBLE);
                holder.left_head.setVisibility(View.VISIBLE);
                holder.message.setGravity(Gravity.LEFT);
                holder.right_head.setVisibility(View.INVISIBLE);
            }
            else{
                Glide.with(getActivity()).load(new MyApplication().imagebaseurl+mData.get(position).get("picture").toString()).placeholder(R.drawable.dog).into(holder.right_head);
                holder.left_head.setVisibility(View.INVISIBLE);
                holder.left_name.setVisibility(View.INVISIBLE);
                holder.right_head.setVisibility(View.VISIBLE);
                holder.message.setGravity(Gravity.RIGHT);
            }

        }

        @Override
        public int getItemCount() {
            return mData.size();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isActivite = false;
        Log.w("com.chat","暂停了!`");
    }

    @Override
    public void onResume() {
        super.onResume();
        isActivite = true;
        Log.w("com.chat","恢复了Resume!`");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isActivite = false;
        Log.e("com.chat","销毁了!");
    }
}
